﻿using Furion;
using Furion.DatabaseAccessor;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Furion.UnifyResult;
using JoyAdmin.Core;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TulingMember.Application.Dto;
using TulingMember.Core; 
using Yitter.IdGenerator;

namespace TulingMember.Application
{
    public class CustomerService : IDynamicApiController
    {
        private readonly ILogger _logger; 
        private readonly IRepository<cts_Customer> _customerRepository;
        private readonly IRepository<cts_CustomerPayLog> _customerpaylogRepository;
        public CustomerService(ILogger logger 
            , IRepository<cts_Customer> customerRepository
            , IRepository<cts_CustomerPayLog> customerpaylogRepository)
        {
            _logger = logger;
            _customerRepository = customerRepository;
            _customerpaylogRepository = customerpaylogRepository;
        }

        
        #region 客户管理
        /// <summary>
        /// 列表
        /// </summary> 
        public PagedList<cts_Customer> SearchCustomer(BaseInput input)
        {
            var search = _customerRepository.AsQueryable(); 
            if (!string.IsNullOrEmpty(input.keyword))
            {
                search = search.Where(m => m.Name.Contains(input.keyword)
                || m.Phone.Contains(input.keyword)  );
            }
            var amount = search.Sum(m=>m.Balance);
            UnifyContext.Fill(new
            {
                Balance = amount,
            });
            return search.ToPagedList(input.page, input.size);
        }
        /// <summary>
        /// 保存客户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine("customer")]
        [UnitOfWork]
        public void SaveCustomer(cts_Customer input)
        {
            var oldCount= _customerRepository.Where(m=>m.Name.Equals(input.Name)&&m.Id!=input.Id).Count();
            if (oldCount>0)
            {
                throw Oops.Bah("名称已存在，请检查").StatusCode(ErrorStatus.ValidationFaild);
            }
            if (input.Id > 0)
            {
                _customerRepository.UpdateExclude(input,new string[] { nameof(input.Balance) });
            }
            else {
                input.Id=YitIdHelper.NextId();
                _customerRepository.Insert(input);
                
                if (input.Balance!=0)
                {
                    _customerpaylogRepository.Insert(new cts_CustomerPayLog
                    {
                        CustomerId=input.Id,
                        CustomerName=input.Name, 
                        ChangeAmount=input.Balance, 
                        NewAmount=input.Balance,  
                        OrderDate=DateTime.Now.Date,
                        Remark="期初账目"
                    });
                }
            } 
            
        }

        /// <summary>
        /// 获取 
        /// </summary>  
        public cts_Customer GetCustomer(long id)
        {
           return  _customerRepository.FindOrDefault(id);
        }
        /// <summary>
        /// 删除 
        /// </summary>  
        [SecurityDefine("customer")]
        public void DeleteCustomer(long id)
        {
            _customerRepository.FakeDelete(id);
        }

        /// <summary>
        /// 客户账目明细
        /// </summary> 
        public PagedList<cts_CustomerPayLog> SearchCustomerPayLog(BaseInput input)
        {
            var search = _customerpaylogRepository.Where(m=>m.CustomerId==input.customerid);
            if (input.sdate != null)
            {
                search = search.Where(m => m.CreatedTime >= input.sdate);
            }
            if (input.edate != null)
            {
                var edate = input.edate?.AddDays(1).Date;
                search = search.Where(m => m.CreatedTime < edate);
            }
            return search.OrderByDescending(m=>m.OrderDate).ThenByDescending(m=>m.Id).ToPagedList(input.page, input.size);
        }
        /// <summary>
        /// 新增一条账目明细
        /// </summary> 
        [SecurityDefine("customer")]
        [UnitOfWork]
        public void AddCustomerPayLog(cts_CustomerPayLog input)
        {
            var customer = _customerRepository.FindOrDefault(input.CustomerId);
            var changeAmount = input.ChangeAmount + input.DiscountAmount;
            input.OldAmount = customer.Balance;
            input.NewAmount = customer.Balance + changeAmount;
            customer.Balance += changeAmount;
            _customerpaylogRepository.Insert(input); 
        }
        #endregion



    }
}
